﻿#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import common
import logging

class SearchError(common.CommandError):
    pass

class SearchCommand(common.Command):
    def __init__(self, repository):
        self.__rep = repository
        self.__logger = logging.getLogger("SearchCommand")

    def execute(self, full_name=None, status=None, name=None, get_all=False):
        try:
            return self.__do_execute(full_name, status, name, get_all)
        except SearchError, ex:
            __logerror__(self.__logger, ex)
            raise
        except Exception, ex:
            __logerror__(self.__logger, ex)
            raise SearchError("Unable to find packet")

    def __do_execute(self, full_name=None, status=None, name=None, get_all=False):
        temp = []

        if not full_name in [None, ""]:
            self.__logger.debug("Will search packets with full_name = %s ", full_name)
            temp.append(set([self.__rep.find_packet_by_fullname(full_name)]))

        if not status in [None, ""]:
            self.__logger.debug("Will search packets with status = %s ", status)
            temp.append(set(self.__rep.find_packets_by_status(status)))

        if not name in [None, ""]:
            self.__logger.debug("Will search packets with name = %s ", name)
            temp.append(set(self.__rep.find_packets_by_name(name)))

        if get_all:
            self.__logger.debug("Will search all packets. Get all = %s ", get_all)
            temp.append(set(self.__rep.get_all()))

        result = list(reduce(lambda x,y: x & y, temp))
        self.__logger.debug("[%s] packets has been found", len(result))

        return result